package com.yonder.gocommand.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.yonder.gocommand.entity.User;
import com.yonder.gocommand.service.IUserService;

@Controller
@RequestMapping("/login")
public class LoginController {

	private User user;

	@Autowired
	private IUserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView handleLoginRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

		ModelAndView mav = new ModelAndView("login");
		
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		
		if (authenticate(username, password) == true) {
			System.out.println("ok");
		} else {
			System.out.println("not ok");
		}
		return mav;
	}
		
	public final boolean authenticate(final String username, final String password) {
		if (user == null) {
			user = userService.existUser(username);
			if (user != null)
				if (user.getPassword().equals(password)) {
					user.setUserRole(user.getUserRole());
					return true;
				}
		}
		return false;
	}
}
